<template>
  <div class="sellingHouse">
    <div class="container">
      <div class="w">
        <div class="card">
          <div class="tabs">
            <a href="javascript:;" :class="isActive == 0 ? 'active' : ''" @click="changeActive(0)">我要卖房</a>
            <!-- <a href="javascript:;" :class="isActive == 1 ? 'active' : ''" @click="changeActive(1)">我要出租</a> -->
          </div>
          <!-- 表单 -->
          <div class="info">
            <el-form :model="houseForm" :rules="rules" ref="houseForm" label-width="130px" class="demo-houseForm">

              <el-form-item label="小区名称" prop="estate">
                <el-autocomplete class="inline-input" v-model="houseForm.estate" :fetch-suggestions="querySearch" placeholder="请输入小区名或楼盘" :trigger-on-focus="false" @select="handleSelect" clearable style="width: 570px" @clear="houseForm.estateId = ''" @change="houseForm.estateId = ''"></el-autocomplete>
              </el-form-item>

              <el-form-item label="栋阁房号" prop="houseNumber">
                <el-input class="houseNumber" v-model="houseForm.dgName" placeholder="楼栋号" autocomplete="off"></el-input>
                <el-input class="houseNumber" v-model="houseForm.number" placeholder="门牌号" autocomplete="off"></el-input>
              </el-form-item>

              <el-form-item label="户型" prop="houseKind">
                <el-select class="kind" v-model="houseForm.kind1" placeholder="室">
                  <el-option v-for="item in options.kind1" :key="item" :label="item" :value="item"></el-option>
                </el-select>
                <el-select class="kind" v-model="houseForm.kind2" placeholder="厅">
                  <el-option v-for="item in options.kind2" :key="item" :label="item" :value="item"></el-option>
                </el-select>
                <el-select class="kind" v-model="houseForm.kind3" placeholder="卫">
                  <el-option v-for="item in options.kind3" :key="item" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item class="price" v-show="isActive == 0" label="期望价格" prop="sup">
                <el-input v-model="houseForm.sup" placeholder="您期望售出的价格" autocomplete="off" onkeyup="value=value.replace(/[^\d\.]/g,'')"></el-input>
                <span class="unit">万元</span>
              </el-form-item>

              <el-form-item class="area" label="建筑面积" prop="builtArea">
                <el-input v-model="houseForm.builtArea" placeholder="您房屋的建筑面积" autocomplete="off" onkeyup="value=value.replace(/[^\d\.]/g,'')"></el-input>
                <span class="unit">㎡</span>
              </el-form-item>

              <el-form-item class="user-name" label="姓名" prop="userName">
                <el-input v-model="houseForm.userName" placeholder="怎么称呼您" autocomplete="off"></el-input>
                <div class="sex fr">
                  <a href="javascript:;" :class="houseForm.sex == 1 ? 'active' : ''" @click="changeSex(1)">先生</a>
                  <a href="javascript:;" :class="houseForm.sex == 0 ? 'active' : ''" @click="changeSex(0)">女士</a>
                </div>
              </el-form-item>

              <el-form-item label="手机号" prop="userPhone">
                <el-input class="phone" v-model="houseForm.userPhone" placeholder="您的联系方式, 我们会及时和您联系" onkeyup="this.value=this.value.replace(/\D/g,'')"></el-input>
                <!-- <el-button class="fr" type="primary">获取验证码</el-button> -->
              </el-form-item>

              <el-form-item>
                <el-button class="confirm" type="primary" @click="submitForm('houseForm')">确认提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import UploaderFile from "@/components/UploaderFile";
import "@/assets/less/sellingHouse.less";
import Data from "@/assets/js/data";
export default {
  name: "SellingHouse",
  components: {
    UploaderFile,
  },

  data() {
    return {
      isActive: 0,
      areaData: [],
      estateList: [],
      // 表单
      houseForm: {
        estate: "", // 小区
        estateId: '',// 小区id
        dgName: "", // 楼栋号
        number: "", // 门牌号
        houseNumber: "", // 栋阁房号dgName+number
        houseKind: "", // 户型
        kind1: '',
        kind2: '',
        kind3: '',
        sup: "", // 卖出价格
        builtArea: "", // 建筑面积
        // insideArea: "", // 套内面积
        // type: "", // 房源类型
        // city: "", // 所在城市
        // areaPlace: "", // 所在区域
        // structure: "",// 房源结构
        // floor: "", // 楼层
        // floor2: "", // 总楼层
        // orientation: "",// 朝向
        // decoration: "",// 装修类型
        // lab: [],
        // status: "",
        // img: "",// 房源图片
        // detailImg: [],// 详情图片
        // desc: "", // 房源描述
        userName: "", // 用户姓名
        sex: 1, // 用户性别  0=>女士/1=>先生
        userPhone: "", // 手机号
        // code: "", // 验证码
      },
      // 表单验证
      rules: {
        estate: [{ validator: this.validEstate, trigger: "blur" }],
        // houseNumber: [{ validator: this.validHouseNumber, trigger: "blur" }],
        // houseKind: [{ validator: this.validHouseKind, trigger: "change" }],
        // kind1: [{ validator: this.validKind1, trigger: "change" }],
        // kind2: [{ validator: this.validKind2, trigger: "change" }],
        // kind3: [{ validator: this.validKind3, trigger: "change" }],
        sup: [{ validator: this.validSup, trigger: "blur" }],
        builtArea: [{ validator: this.validBuiltArea, trigger: "blur" }],
        // insideArea: [{ validator: this.validInsideArea, trigger: "blur" }],
        // type: [{ validator: this.validType, trigger: "blur" }],
        // city: [{ validator: this.validCity, trigger: "change" }],
        areaPlace: [{ validator: this.validAreaPlace, trigger: "change" }],
        // structure: [{ validator: this.validStructure, trigger: "change" }],
        floor: [{ validator: this.validFloor, trigger: "change" }],
        floor2: [{ validator: this.validFloor2, trigger: "blur" }],
        // orientation: [{ validator: this.validOrientation, trigger: "change" }],
        // decoration: [{ validator: this.validDecoration, trigger: "change" }],
        // img: [{ validator: this.validImg, trigger: "change" }],
        // detailImg: [{ validator: this.validdetailImg, trigger: "change" }],
        // desc: [{ validator: this.validDesc, trigger: "blur" }],
        userName: [{ validator: this.validUsername, trigger: "blur" }],
        userPhone: [{ validator: this.validPhone, trigger: "blur" }],
        code: [{ validator: this.validCode, trigger: "blur" }],
      },

      options: {
        // 户型-室
        kind1: ["1室", "2室", "3室", "4室", "5室", "6室", "7室", "8室", "9室"],
        // 户型-厅
        kind2: ["1厅", "2厅", "3厅", "4厅", "5厅", "6厅", "7厅", "8厅", "9厅"],
        // 户型-卫
        kind3: ["1卫", "2卫", "3卫", "4卫", "5卫", "6卫", "7卫", "8卫", "9卫"],
        // 房源类型
        // type: ["住宅", "公寓", "别墅"],
      },
    };
  },

  created() {
    let isLogin = false;
    if (this.$cookies.get('__tk')) {
      isLogin = true;
    } else {
      isLogin = false;
    }
    let oj = {
      title: '卖房',
      nav: 'SellingHouse',
      isLogin: isLogin
    };
    this.$emit('isTitle', oj);
    this.areaData = [...Data];
    this.areaData.shift();
    for (let key of this.areaData) {
      key.children.shift();
    }
    // console.log(this.areaData)
    this.loadAll()
  },

  mounted() {
    // this.estateList = this.loadAll();
    this.$nextTick(() => {
      document.body.scrollTo(0, 0);
      window.scrollTo(0, 0);
      document.getElementById('index').scrollTop = 0
      window.pageYOffset = 0;
    })
  },

  methods: {
    // 跳转
    goPage(n) {
      this.$router.push({ name: n });
    },

    // 切换选项卡
    changeActive(i) {
      if (this.isActive == i) {
        return;
      }
      this.isActive = i;
    },

    // 切换性别
    changeSex(s) {
      if (this.houseForm.sex == s) {
        return;
      }
      this.houseForm.sex = s;
    },

    // 小区输入框的输入建议
    querySearch(queryString, cb) {
      var estateList = this.estateList;
      var results = queryString ? estateList.filter(this.createFilter(queryString)) : estateList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (estate) => {
        return (estate.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    // 获取所有小区名,地址和id
    loadAll() {
      this.axios({
        method: 'get',
        url: this.baseUrl + '/getEstate',
      }).then(res => {
        console.log('res==>', res)
        if (res.data.code == 200) {
          // let arr = [];
          res.data.data.forEach(e => {
            let o = { "value": '', "address": '', "estateId": '' };
            o["value"] = e.estateName;
            o["address"] = e.address;
            o["estateId"] = e.estateId;
            // arr.push(o);
            this.estateList.push(o);
          });
          // console.log('arr==>', arr)
          // console.log('this.estateList==>', this.estateList)
        }
      }).catch(err => {
        console.log('err==>', err)

      })
      // return arr;
    },
    // 保存小区id
    handleSelect(item) {
      console.log(item);
      this.houseForm.estateId = item.estateId;
    },
    // 验证小区名
    validEstate(rule, value, callback) {
      if (!value) {
        callback(Error("请输入小区名或楼盘"))
      } else {
        callback();
      }
    },
    // 验证栋阁房号
    // validHouseNumber(rule, value, callback) {
    //   if (!this.houseForm.dgName) {
    //     // return this.$message.warning("请输入楼栋号")
    //     callback(Error("请输入楼栋号"));
    //   }
    //   if (!this.houseForm.number) {
    //     // return  this.$message.warning("请输入门牌号")
    //     callback(Error("请输入门牌号"));
    //   }
    //   value = this.houseForm.dgName + "栋" + this.houseForm.number + "房";
    //   // 拼接栋阁房号字符串
    //   console.log("dgName + number ==> ", value);
    //   callback();
    // },

    // 验证户型
    // validHouseKind(rule, value, callback) {
    //   if (!this.houseForm.kind1) {
    //     // return this.$message.warning("请选择几厅");
    //     callback(Error("请选择几室"));
    //   }
    //   if (!this.houseForm.kind2) {
    //     // return this.$message.warning("请选择几厅");
    //     callback(Error("请选择几厅"));
    //   }
    //   if (!this.houseForm.kind3) {
    //     // return this.$message.warning("请选择几厅");
    //     callback(Error("请选择几卫"));
    //   }
    //   value = this.houseForm.kind1 + "室" + this.houseForm.kind2 + "厅" + this.houseForm.kind3 + "卫";
    //   // 拼接栋阁房号字符串
    //   console.log("户型 ==> ", value);
    //   callback();
    // },

    // 
    // validKind1(rule, value, callback){
    //   if(!value){
    //     callback(new Error('请选择有几室'))
    //   }else{
    //     callback()
    //   }
    // },

    // 验证价格
    validSup(rule, value, callback) {
      if (!value) {
        callback(Error("请输入价格"));
      } else {
        callback()
      }
    },

    // 验证建筑面积
    validBuiltArea(rule, value, callback) {
      if (!value) {
        callback(Error("请输入建筑面积"));
      } else {
        callback();
      }
    },

    // 验证套内面积
    // validInsideArea(rule, value, callback) {
    //   if (!value) {
    //     callback(Error("请输入套内面积"));
    //     return;
    //   }
    // },

    // 验证房源结构
    // validStructure(rule, value, callback) {
    //   if (!value) {
    //     callback(Error("请选择房源结构"));
    //     return;
    //   }
    // },

    // 验证楼层
    // validFloor(rule, value, callback) {
    //   if (!value) {
    //     callback(Error("请选择楼层"));
    //     return;
    //   }
    // },

    // 验证楼层总数
    // validFloor2(rule, value, callback) {
    //   if (!value) {
    //     callback(Error("请输入价格"));
    //     return;
    //   }
    // },

    // 验证朝向
    // validOrientation(rule, value, callback) {},

    // 验证房源装修
    // validDecoration(rule, value, callback) {},

    // 验证图片
    // validImg(rule, value, callback) {},

    // 验证详细图片
    // validdetailImg(rule, value, callback) {},

    // 验证详情
    // validDesc(rule, value, callback) {},

    // 验证姓名
    validUsername(rule, value, callback) {
      if (!value) {
        callback(Error("请输入姓名"));
      } else {
        callback();
      }
    },

    // 验证手机号
    validPhone(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        callback(new Error("手机格式错误!"));
      } else {
        callback();
      }
    },

    // 表单验证
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.houseForm.estateId) {
            this.$message.warning("请输入有效的小区名或楼盘")
            return
          }
          if (!this.houseForm.dgName || !this.houseForm.number) {
            this.$message.warning("请填写完整栋阁房号");
            return
          } else {
            this.houseForm.houseNumber = this.houseForm.dgName + '栋' + this.houseForm.number + '房';
            console.log('houseNumber==>', this.houseForm.houseNumber)
          }
          if (!this.houseForm.kind1 || !this.houseForm.kind2 || !this.houseForm.kind3) {
            this.$message.warning("请填写完整户型");
            return
          } else {
            this.houseForm.houseKind = this.houseForm.kind1 + this.houseForm.kind2 + this.houseForm.kind3;
            console.log('kind==>', this.houseForm.houseKind)
          }
          //发起发布房源请求
          console.log("发起发布房源请求");
          let sex = this.houseForm.sex == 0 ? '女士' : '先生';
          console.log('kind1', parseInt(this.houseForm.kind1))
          this.axios({
            method: 'post',
            url: this.baseUrl + '/addHouse',
            data: {
              estateId: this.houseForm.estateId,
              houseNum: this.houseForm.houseNumber,
              kind: this.houseForm.houseKind,
              userName: this.houseForm.userName + sex,
              userPhone: this.houseForm.userPhone,
              sup: this.houseForm.sup,
              builtArea: this.houseForm.builtArea,
              sub: Math.round((Number(this.houseForm.sup)) / (Number(this.houseForm.builtArea)) * 10000),
              kind1: parseInt(this.houseForm.kind1),
              kind2: parseInt(this.houseForm.kind2),
              kind3: parseInt(this.houseForm.kind3),
            },
          }).then(res => {
            console.log('res==>', res)
            if (res.data.code == 200) {
              this.$message.success(res.data.msg)
              this.houseForm = {
                estate: "", // 小区
                estateId: '',// 小区id
                dgName: "", // 楼栋号
                number: "", // 门牌号
                houseNumber: "", // 栋阁房号dgName+number
                houseKind: "", // 户型
                kind1: '',
                kind2: '',
                kind3: '',
                sup: "", // 卖出价格
                builtArea: "", // 建筑面积
                userName: "", // 用户姓名
                sex: 1, // 用户性别  0=>女士/1=>先生
                userPhone: "", // 手机号
              }
            } else {
              this.$message.error(res.data.msg)
            }
          }).catch(err => {
            console.log('err==>', err)
            this.$message.error(err)
          })
        } else {
          this.$message.warning("请填写完整相关资料");
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>